package com.jeeplus.modules.api.utils;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;

import com.jeeplus.common.utils.MD5Util;
import com.taobao.api.Constants;

import com.alibaba.fastjson.JSONObject;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.net.HttpClientUtil;


import static com.taobao.api.internal.util.TaobaoUtils.encryptMD5;

/**
 * 京东联盟
 * @author ws
 *
 */
public class JdOfficialUtils {

	public static final String appkey = "880526d17beb4ef6afe0ac3b22fa9304";// appkey
	public static final String siteId = "1937737514";// 站点ID（也是京东联盟的APPID）
	public static final String secretkey = "72380da54bad4ba6ab41df1f8dc8b34e";// 京东联盟授权secretkey
	public static final String SERVER_URL = "https://router.jd.com/api?";// 根据skuid查询商品信息接口
	public static final String jingfen = "jd.union.open.goods.jingfen.query";// 京粉精选商品查询接口
	public static final String promotiongoodsinfo = "jd.union.open.goods.promotiongoodsinfo.query";//  根据skuid查询商品信息接口版本1.0
	public static final String accessToken = "jd.union.open.goods.jingfen.query";//
	public static final String goodsItemCateInfo = "jd.union.open.category.goods.get ";// 京东商品类目查询
	public static final String goodsJdUnionItems = "jd.union.open.goods.query";// 京东商品查询API
	public static final String bigfield = "jd.union.open.goods.bigfield.query";// 获取商品综合信息
	public static final String doItempid = "jd.union.open.user.pid.get";// 创建推广位pid


	public static void main(String[] args) {
	}

	/**
	 * 京东联盟推广链接
	 *
	 * @param url    API接口路径
	 *               type 接口名字
	 * @param params 业务参数
	 * @return
	 */
	public static JSONObject JDAPI(String url, String type, Map<String, String> params) {
		params.put("method", type);
		params.put("app_key", appkey);
		SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");

		params.put("timestamp", sdf.format(new Date()));
		params.put("format", "json");
		params.put("v", "1.0");
		params.put("sign_method", "md5");

		String url2 = getSign(params);
		String sign = secretkey + url2 + secretkey;
		sign = MD5Util.md5(sign).toUpperCase();
		params.put("sign", sign);

		String resultString = HttpClientUtil.doPost(url, params);
		return StringUtils.isNotBlank(resultString) ? JSONObject.parseObject(resultString) : new JSONObject();
	}

	public static String getParams(Map<String, String> map) {
		String result = "";
		try {
			TreeMap<String, String> treeMap = new TreeMap<>(map);

			// 构造签名键值对的格式
			StringBuilder sb = new StringBuilder();
			Iterator<Entry<String, String>> iterator = treeMap.entrySet().iterator();
			while (iterator.hasNext()) {
				Entry<String, String> entry = iterator.next();
				String key = entry.getKey();
				String val = entry.getValue();
				//String val = URLEncoder.encode(entry.getValue(), "utf8");
				sb.append(key).append("=").append(val).append("&");
			}
			result = StringUtils.removeEnd(sb.toString(), "&");
			System.out.println("sb:" + result);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	public static String getDuoduoParams(Map<String, String> map) {
		String result = "";
		try {
			Map<String, String> params = new TreeMap<String, String>(
				new Comparator<String>() {
					public int compare(String obj1, String obj2) {
						// 升序排序
						return obj1.compareTo(obj2);
					}
			});
			TreeMap<String, String> treeMap = new TreeMap<>(map);

			// 构造签名键值对的格式
			StringBuilder sb = new StringBuilder();
			Iterator<Entry<String, String>> iterator = treeMap.entrySet().iterator();
			while (iterator.hasNext()) {
				Entry<String, String> entry = iterator.next();
				String key = entry.getKey();
				String val = entry.getValue();
				//String val = URLEncoder.encode(entry.getValue(), "utf8");
				sb.append(key).append(val);
			}
			result = sb.toString();
			System.out.println("sb:" + result);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	public static String signTopRequest(Map<String, String> params, String secret, String signMethod) throws IOException {
		// 第一步：检查参数是否已经排序
		String[] keys = params.keySet().toArray(new String[0]);
		Arrays.sort(keys);

		// 第二步：把所有参数名和参数值串在一起
		StringBuilder query = new StringBuilder();
		if (Constants.SIGN_METHOD_MD5.equals(signMethod)) {
			query.append(secret);
		}
		for (String key : keys) {
			String value = params.get(key);
				query.append(key).append(value);
		}

		// 第三步：使用MD5/HMAC加密
		byte[] bytes;
			query.append(secret);
			bytes = encryptMD5(query.toString());

		// 第四步：把二进制转化为大写的十六进制(正确签名应该为32大写字符串，此方法需要时使用)
		return byte2hex(bytes);
	}
	public static String byte2hex(byte[] bytes) {
		StringBuilder sign = new StringBuilder();
		for (int i = 0; i < bytes.length; i++) {
			String hex = Integer.toHexString(bytes[i] & 0xFF);
			if (hex.length() == 1) {
				sign.append("0");
			}
			sign.append(hex.toUpperCase());
		}
		return sign.toString();
	}
	/**
	 * 生成签名
	 * @param map
	 * @return
	 */
	public static String getSign(Map<String, String> map) {

		String result = "";
		try {
			List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(map.entrySet());
			// 对所有传入参数按照字段名的 ASCII 码从小到大排序（字典序）
			Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>() {

				public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
					return (o1.getKey()).toString().compareTo(o2.getKey());
				}
			});

			// 构造签名键值对的格式
			StringBuilder sb = new StringBuilder();
			for (Map.Entry<String, String> item : infoIds) {
				if (item.getKey() != null || item.getKey() != "") {
					String key = item.getKey();
					String val = item.getValue();
					if (!(val == "" || val == null)) {
						sb.append(key +val);
					}
				}

			}
			result = sb.toString();
		} catch (Exception e) {
			return null;
		}
		return result;
	}
}
